package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * ClassName: ThreadPoolConfig
 * Package: com.spzx.channel.config
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/3/24 20:51
 * @Version 1.0
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {

        //获取当前服务器的核心线程数量
        int corePoolSize = Runtime.getRuntime().availableProcessors();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,//线程池的核心线程数
                corePoolSize * 2,//最大线程数，一般情况下设置为核心线程数的两倍或者三倍。
                60L,//核心线程以外的线程保持活跃的时间
                TimeUnit.SECONDS,//时间单位
                new LinkedBlockingDeque<>(100),//队列中存储的任务数量
                Executors.defaultThreadFactory(),//线程工厂，一般情况下使用默认的即可
//                new ThreadPoolExecutor.CallerRunsPolicy()//拒绝策略，调用者执行策略
                //自定义拒绝策略
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        //再次提交
                        executor.execute(r);
                    }
                }
        );
        //线程在需要的时候创建，节省服务器资源
        return threadPoolExecutor;
    }
}